from threading import Thread
import sys
from time import sleep, time
from datetime import datetime
import libs.zabbix_api
from libs.zabbix_menu import zabbix_menu
from libs.zabbix_trigger import zabbix_trigger

class zabbix_poller(Thread):
	__keeprunning = True
	__ApiConnection = None
	__is_connected = False
	
	menu = None
	configuration = None
	
	def __init__(self, configuration):
		self.configuration = configuration
		
		Thread.__init__(self)

	
	def run(self):
		self.connect()
		
		while self.__keeprunning:
			# Remove menu and recreate it to refill it
			self.new_menu = zabbix_menu(self.configuration)
			self.upperSeverity = 0
			self.now = time()
			self.blinkInterval = 300

			# Process trigger alerts
			for trigger in self.get():
				if trigger.get_severity() > self.upperSeverity:
					self.upperSeverity = trigger.get_severity()
				if (self.now - trigger.get_lastchange()) < self.blinkInterval:
					self.blink = True
				readable_date = str(datetime.fromtimestamp(trigger.get_lastchange()))
				self.new_menu.add_item(readable_date + ': ' + trigger.get_hostname() +
								"\t | " + trigger.get_desc() + " | " + str(trigger.get_severity()))

#				self.notify(trigger)
			
			self.old_menu = self.menu
			self.menu = self.new_menu
			if not self.old_menu == None:
				self.old_menu.destroy()

			self.menu.set_visible(True)
			x=0
			while x <= self.configuration.get_update_interval():
				if not self.__keeprunning == True:
					break
				x+=5
				sleep(5)
				
	def terminate(self):
		self.__keeprunning = False

	def connect(self):
		self.__ApiConnection = libs.zabbix_api.ZabbixAPI(server = self.configuration.get_zabbixserver_hostname())
		self.__ApiConnection.login(self.configuration.get_zabbixserver_username(), self.configuration.get_zabbixserver_password())
		if self.__ApiConnection.test_login() != True:
			print "Login failed"
			sys.exit()
		else:
			self._is_connected = True

	def get(self):
		if not self._is_connected:
			print "Not connected, connect first"
			return

		ApiTriggers = libs.zabbix_api.ZabbixAPITrigger(self.__ApiConnection)
		ApiHosts = libs.zabbix_api.ZabbixAPIHost(self.__ApiConnection)

		triggerOptions = dict(limit = 10,
							extendoutput = True,
							groupCount = True,
							sortfield = 'lastchange',
							sortorder = 'DESC',
							monitored = True,
							only_problems = True,
							)

		triggers = ApiTriggers.get(triggerOptions)
		
		parsedTriggers = []
		for trigger in triggers:
			hostOptions = dict(triggerids = int(trigger['triggerid']),
							extendoutput = True)
			hosts = ApiHosts.get(hostOptions)
			parsedTriggers.append(
				zabbix_trigger(
					trigger['triggerid'],
					hosts[0]['host'],
					str(trigger['description']).replace("{HOSTNAME}", str(hosts[0]['host'])),
					trigger['value'],
					trigger['priority'],
					trigger['lastchange']
				)
			)

		return parsedTriggers

#	def getTriggers(self):
